/**
 * 版权所有 2009-2015 旺晓杨 peonyxy@msn.cn
 **/
package com.cn;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.ac.cintcm.sh.domain.Rule;
import cn.ac.cintcm.sh.domain.View;
import cn.ac.cintcm.sh.service.ViewService;

public class ViewServlet extends HttpServlet {

	/**
     * 
     */
    private static final long serialVersionUID = 7301958196461512773L;
    /**
	 * Constructor of the object.
	 */
	public ViewServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {


		response.setCharacterEncoding("UTF-8");
		String doClass = request.getParameter("doClass");
		if(doClass != null && doClass.equals("view")){
			this.view(request, response);
		}
		else if(doClass != null && doClass.equals("viewRules")){
			this.viewRules(request, response);
		}
		else if(doClass != null && doClass.equals("viewEdit")){
			this.viewEdit(request, response);
		}else if(doClass != null && doClass.equals("viewDel")){
			this.viewDel(request, response);
		}else if(doClass != null && doClass.equals("ruleEdit")){
			this.ruleEdit(request, response);
		}else if(doClass != null && doClass.equals("ruleDel")){
			this.ruleDel(request, response);
		}
		
		
	}
	

	/**
	 *  删除规则
	 * @param request
	 * @param response
	 */
	private void ruleDel(HttpServletRequest request, HttpServletResponse response){
		String[] ids = request.getParameterValues("ids");
		String viewId = request.getParameter("viewId");
		ViewService viewService = new ViewService();
		String[] storeIds = request.getParameterValues("storeIds");
		 StringBuffer str = new StringBuffer("");
		 StringBuffer s = new StringBuffer("");
		 List l = new ArrayList();
		 PrintWriter out = null;
		try {
			 out = response.getWriter();
			
			 if(ids != null && ids.length > 0){
				 int size = ids.length;
				 
				 for(int i=0 ;i < size ; i++){
					viewService.deleteRule(viewId, ids[i]);
					 l.add(storeIds[i]);
				 }
			 }
			
			str.append("{'successFn':true,storeId:"+net.sf.json.JSONArray.fromObject(l)+"}");
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println(this.getClass()+":删除规则错误!");
			str.append("{'successFn':false,storeId:"+net.sf.json.JSONArray.fromObject(l)+"}");
		}
		if(out != null)
		{
			out.print(str);
		}	
	}

	/**
	 * 修改/添加规则
	 * @param request
	 * @param response
	 */
	private void ruleEdit(HttpServletRequest request, HttpServletResponse response){
		String id = request.getParameter("id");
		String unit = request.getParameter("unit");
		
		String quantity = request.getParameter("quantity");
		String herbName = request.getParameter("herbName");
		String storeId = request.getParameter("storeId");
		String viewId = request.getParameter("viewId");
		ViewService viewService = new ViewService();
		 StringBuffer str = new StringBuffer("");
		 PrintWriter out = null;
		try {
			 out = response.getWriter();
			int rId = -1;
			if(id != null &&!id.equals("")){
				viewService.updateRule(id, unit, quantity, herbName);
				rId = Integer.parseInt(id);
			}else{
				rId= viewService.addRule(viewId, unit, quantity, herbName);
			}
			str.append("{'successFn':true,'rId':'"+rId+"',storeId:'"+storeId+"'}");
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println(this.getClass()+":更新或修改规则错误!");
			str.append("{'successFn':false,storeId:'"+storeId+"'}");
		}
		if(out != null)
			out.print(str);
			
	}
	/**
	 * 删除观点
	 * @param request
	 * @param response
	 */
	private void viewDel(HttpServletRequest request, HttpServletResponse response){
		String[] id = request.getParameterValues("ids");
		
		ViewService viewService = new ViewService();
		 StringBuffer str = new StringBuffer("");
		 PrintWriter out = null;
		try {
			 out = response.getWriter();
			 if(id != null){
				 int size = id.length;
				 for(int i = 0 ; i<size ; i++){
					 viewService.deleteView(id[i]);
				 }
			 }
			str.append("{'successFn':true}");
		} catch (Exception e) {
			System.err.println(this.getClass()+":删除观点错误!");
			str.append("{'successFn':false}");
		}
		if(out != null)
			out.print(str);
			
	}
	/**
	 * 修改观点
	 * @param request
	 * @param response
	 */
	private void viewEdit(HttpServletRequest request, HttpServletResponse response){
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String storeId = request.getParameter("storeId");
		ViewService viewService = new ViewService();
		 StringBuffer str = new StringBuffer("");
		 PrintWriter out = null;
		try {
			 out = response.getWriter();
			int vId = -1;
			if(id != null &&! id.equals("")){
				View view = viewService.updateView(id, name);
				vId = view.getId();
			}else{
				vId= viewService.addView(name);
			}
			str.append("{'successFn':true,'vId':'"+vId+"',storeId:'"+storeId+"'}");
		} catch (Exception e) {
			System.err.println(this.getClass()+":更新或修改观点错误!");
			str.append("{'successFn':false,storeId:'"+storeId+"'}");
		}
		if(out != null)
			out.print(str);
			
	}

	/**
	 * 获得所有观点
	 * @param request
	 * @param response
	 */
	private void view(HttpServletRequest request, HttpServletResponse response){
		
		 PrintWriter out = null;
		 StringBuffer str = new StringBuffer("");
			try {
				ViewService viewService = new ViewService();
				  str.append("{articles:"+net.sf.json.JSONArray.fromObject(viewService.getViews()).toString()+"}");
				  out = response.getWriter();
				} catch (Exception e) {
					System.err.println(this.getClass()+":获得所有观点错误!");
				}
		 out.print(str);
		 out.flush();
	}
	
	/**
	 * 获得观点的则算规则
	 * @param request
	 * @param response
	 */
	private void viewRules(HttpServletRequest request, HttpServletResponse response){
		
		String viewId = request.getParameter("viewId");
		if(viewId != null)
		{
		 PrintWriter out = null;
		 StringBuffer str = new StringBuffer();
			try {
				  out = response.getWriter();
					ViewService viewService = new ViewService();
					View view = viewService.getView(viewId);
					if(!view.getRules().isEmpty()){
						Iterator iterator = view.getRules().values().iterator();
						 str.append("{articles:[");
						if(iterator.hasNext()){
							Rule rule = (Rule) iterator.next();
							str.append("{'id':'");
                            str.append(rule.getId());
                            str.append("','unit':'");
                            str.append(rule.getHerb().getDosage().getUnit());
                            str.append("','quantity':'");
                            str.append(rule.getUnit().getQuantity());
                            str.append("','herbName':'");
                            str.append(rule.getHerb().getName()==null?"":rule.getHerb().getName());
                            str.append("'}");
						}
						while(iterator.hasNext()){
							Rule rule = (Rule) iterator.next();
                            str.append(",{'id':'");
                            str.append(rule.getId());
                            str.append("','unit':'");
                            str.append(rule.getHerb().getDosage().getUnit());
                            str.append("','quantity':'");
                            str.append(rule.getUnit().getQuantity());
                            str.append("','herbName':'");
                            str.append(rule.getHerb().getName()==null?"":rule.getHerb().getName());
                            str.append("'}");
                         }
					}
					
					str.append("]}");
				  
				} catch (Exception e) {
					e.printStackTrace();
					System.err.println(this.getClass()+":获得所有观点错误!");
				}
				out.print(str);
				out.flush();
		}
	}
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}